import logging
import random

from django import http
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView
from django_redis import get_redis_connection

from utils.response_code import RETCODE

from verfications import constants
from verfications.constants import IMAGE_CODE_REDIS_EXPIRES
from verfications.libs.captcha.captcha import captcha
from verfications.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import sned_sms_code
# Create your views here.

logger = logging.getLogger('django')


class VerificationsView(View):
    """图形验证码"""

    def get(self, request, UUID_code):
        """

        :param request:
        :param UUID_code:  uuid
        :return:  返回image
        """
        # 生成图形验证码
        code_text, image = captcha.generate_captcha()
        # 保存图形验证码
        redis_conn = get_redis_connection("Verifications")
        redis_conn.setex(f"img_uuid{UUID_code}", IMAGE_CODE_REDIS_EXPIRES, code_text)
        # 响应图形验证码
        return http.HttpResponse(image, content_type="image/jpg")


class SMScode(View):
    """短信验证码"""
    def get(self, request, mobile):
        """
        :param request:
        :param mobile:  手机号
        :return:
        """
        # 接收参数

        image_code = request.GET.get("image_code")
        uuid = request.GET.get("uuid")
        # 校验参数
        if not all([mobile, uuid, image_code]):
            return http.HttpResponseForbidden("缺少必传参数")



        # 业务逻辑 提取验证码
        redis_conn = get_redis_connection("Verifications")

        # 判断用户是否频繁发送验证码
        send_flag =redis_conn.get(f"sms_flag_{mobile}")
        if  send_flag:
            return http.JsonResponse({
                "code": RETCODE.THROTTLINGERR, "errmsg": "频繁发送短信验证码"
            })


        image_code_server = redis_conn.get(f"img_uuid{uuid}")
        if not image_code_server:
            return http.JsonResponse({
                "code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码失效"
            })

        # 业务逻辑 删除验证码
        redis_conn.delete(f"img_uuid{uuid}")

        # 业务逻辑 对比验证码
        if image_code_server.decode().lower() != image_code.lower():
            return http.JsonResponse({
                "code": RETCODE.IMAGECODEERR, "errmsg": "输入图形验证码错误"
            })


        # 发送短信
        sms_code = random.randint(1000, 9999)
        logger.info("sms_code: %s", sms_code)

             # 创建redis 管道
        pline=redis_conn.pipeline()
             # 将指令添加到队列中
             # 执行命令

        pline.setex(f"sms_code{mobile}", constants.SMS_CODE_REDIS_EXPIRES, sms_code)


        #保存发送短信验证码的标记
        pline.setex(f"sms_flag_{mobile}", constants.SEND_SMS_CODE_INTERVAL,"true")
        pline.execute()
        # 后期使用celery 优化代码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # 使用celery 发送短信 使用 delay 方法
        sned_sms_code.delay(mobile, sms_code)
        # print(sms_code, "发送成功")

        # 响应结果
        return http.JsonResponse({
            "code": RETCODE.OK, "errmsg": "短信发送成功"
        })

    def post(self, request):
        pass
